const { pool } = require('../config/db');
const bcrypt = require('bcrypt');
const jwt = require('jsonwebtoken');
const { addAuditLog } = require('./auditLogController');
require('dotenv').config();

const JWT_SECRET = process.env.JWT_SECRET || 'your-secret-key'; // Fallback secret key
const JWT_EXPIRES_IN = process.env.JWT_EXPIRES_IN || '1h';

/**
 * 用户注册
 */
async function registerUser(req, res) {
  try {
    const { username, password, email } = req.body;

    if (!username || !password || !email) {
      return res.status(400).json({
        success: false,
        message: '用户名、密码和邮箱是必需的'
      });
    }

    // 检查用户名或邮箱是否已存在
    const [existingUsers] = await pool.query(
      'SELECT * FROM users WHERE username = ? OR email = ?',
      [username, email]
    );

    if (existingUsers.length > 0) {
      return res.status(409).json({
        success: false,
        message: '用户名或邮箱已存在'
      });
    }

    // 哈希密码
    const hashedPassword = await bcrypt.hash(password, 10);

    // 插入新用户
    const [result] = await pool.query(
      'INSERT INTO users (username, password, email) VALUES (?, ?, ?)',
      [username, hashedPassword, email]
    );

    // 创建默认用户偏好设置
    await pool.query(
      'INSERT INTO user_preferences (user_id) VALUES (?)',
      [result.insertId]
    );

    // 创建默认通知设置
    await pool.query(
      'INSERT INTO notification_settings (user_id, enable_all) VALUES (?, 1)',
      [result.insertId]
    );

    res.status(201).json({
      success: true,
      message: '用户注册成功',
      data: {
        id: result.insertId,
        username,
        email
      }
    });
  } catch (error) {
    console.error('用户注册失败:', error);
    res.status(500).json({
      success: false,
      message: '用户注册失败',
      error: error.message
    });
  }
}

/**
 * 用户登录
 */
async function loginUser(req, res) {
  try {
    const { username, password, deviceType } = req.body;
    const ipAddress = req.headers['x-forwarded-for'] || req.connection.remoteAddress;
    const userAgent = req.headers['user-agent'] || '';

    if (!username || !password) {
      return res.status(400).json({
        success: false,
        message: '用户名和密码是必需的'
      });
    }

    // 查找用户
    const [users] = await pool.query('SELECT * FROM users WHERE username = ?', [username]);

    if (users.length === 0) {
      // 记录失败的登录尝试
      await addAuditLog({
        user_id: null,
        action: 'login',
        details: {
          username,
          success: false,
          description: '用户名不存在',
          device_type: deviceType || parseUserAgent(userAgent)
        },
        ip_address: ipAddress
      });

      return res.status(401).json({
        success: false,
        message: '用户名或密码错误'
      });
    }

    const user = users[0];

    // 验证密码
    const isPasswordValid = await bcrypt.compare(password, user.password);

    if (!isPasswordValid) {
      // 记录密码错误的登录尝试
      await addAuditLog({
        user_id: user.id,
        action: 'login',
        details: {
          username,
          success: false,
          description: '密码错误',
          device_type: deviceType || parseUserAgent(userAgent)
        },
        ip_address: ipAddress
      });

      return res.status(401).json({
        success: false,
        message: '用户名或密码错误'
      });
    }

    // 生成JWT令牌
    const token = jwt.sign({ id: user.id, username: user.username, role: user.role }, JWT_SECRET, {
      expiresIn: JWT_EXPIRES_IN
    });

    // 记录成功的登录
    await addAuditLog({
      user_id: user.id,
      action: 'login',
      details: {
        username,
        success: true,
        description: '登录成功',
        device_type: deviceType || parseUserAgent(userAgent)
      },
      ip_address: ipAddress
    });

    res.json({
      success: true,
      message: '登录成功',
      data: {
        token,
        user: {
          id: user.id,
          username: user.username,
          email: user.email,
          role: user.role
        }
      }
    });
  } catch (error) {
    console.error('用户登录失败:', error);
    res.status(500).json({
      success: false,
      message: '用户登录失败',
      error: error.message
    });
  }
}

/**
 * 获取当前用户信息
 */
async function getCurrentUser(req, res) {
  let connection;
  try {
    const userId = req.user.id; // 从认证中间件获取用户ID

    connection = await pool.getConnection();
    // 获取用户基本信息
    const [users] = await connection.query(
      'SELECT id, username, email, phone, city, housing_type, family_members, role, created_at FROM users WHERE id = ?', 
      [userId]
    );

    if (users.length === 0) {
      return res.status(404).json({
        success: false,
        message: '用户未找到'
      });
    }

    // 获取用户的默认家庭信息
    const [families] = await connection.query(
      'SELECT f.id, f.name FROM users u JOIN families f ON u.default_family_id = f.id WHERE u.id = ?',
      [userId]
    );

    const userData = users[0];
    if (families.length > 0) {
      userData.default_family = families[0];
    }

    res.json({
      success: true,
      data: userData
    });
  } catch (error) {
    console.error('获取用户信息失败:', error);
    res.status(500).json({
      success: false,
      message: '获取用户信息失败',
      error: error.message
    });
  } finally {
    if (connection) {
      connection.release();
    }
  }
}

/**
 * 更新用户信息
 */
async function updateUser(req, res) {
  let connection;
  try {
    const userId = req.user.id;
    const { email, phone, city, housing_type, family_members } = req.body;

    // 构建更新字段
    const updateFields = {};
    
    connection = await pool.getConnection();
    
    // 只更新提供的字段
    if (email !== undefined) {
      // 如果提供了邮箱，检查是否已被其他用户使用
      const [existingUsers] = await connection.query(
        'SELECT * FROM users WHERE email = ? AND id != ?',
        [email, userId]
      );

      if (existingUsers.length > 0) {
        return res.status(409).json({
          success: false,
          message: '邮箱已被其他用户使用'
        });
      }
      
      updateFields.email = email;
    }
    
    if (phone !== undefined) updateFields.phone = phone;
    if (city !== undefined) updateFields.city = city;
    if (housing_type !== undefined) updateFields.housing_type = housing_type;
    if (family_members !== undefined) updateFields.family_members = parseInt(family_members) || 1;

    // 检查是否有要更新的字段
    if (Object.keys(updateFields).length === 0) {
      return res.status(400).json({
        success: false,
        message: '没有提供要更新的字段'
      });
    }

    // 更新用户信息
    await connection.query('UPDATE users SET ? WHERE id = ?', [updateFields, userId]);

    res.json({
      success: true,
      message: '用户信息已更新',
      data: {
        id: userId,
        ...updateFields
      }
    });
  } catch (error) {
    console.error('更新用户信息失败:', error);
    res.status(500).json({
      success: false,
      message: '更新用户信息失败',
      error: error.message
    });
  } finally {
    if (connection) {
      connection.release();
    }
  }
}

/**
 * 修改密码
 */
async function changePassword(req, res) {
  let connection;
  try {
    const userId = req.user.id;
    const { currentPassword, newPassword } = req.body;

    if (!currentPassword || !newPassword) {
      return res.status(400).json({
        success: false,
        message: '当前密码和新密码都是必需的'
      });
    }

    connection = await pool.getConnection();
    
    // 获取用户当前密码
    const [users] = await connection.query('SELECT password FROM users WHERE id = ?', [userId]);

    if (users.length === 0) {
      return res.status(404).json({
        success: false,
        message: '用户未找到'
      });
    }

    const user = users[0];

    // 验证当前密码
    const isCurrentPasswordValid = await bcrypt.compare(currentPassword, user.password);

    if (!isCurrentPasswordValid) {
      return res.status(401).json({
        success: false,
        message: '当前密码错误'
      });
    }

    // 哈希新密码
    const hashedNewPassword = await bcrypt.hash(newPassword, 10);

    // 更新密码
    await connection.query('UPDATE users SET password = ? WHERE id = ?', [hashedNewPassword, userId]);

    res.json({
      success: true,
      message: '密码已修改'
    });
  } catch (error) {
    console.error('修改密码失败:', error);
    res.status(500).json({
      success: false,
      message: '修改密码失败',
      error: error.message
    });
  } finally {
    if (connection) {
      connection.release();
    }
  }
}

/**
 * 获取用户偏好设置
 */
async function getUserPreferences(req, res) {
  let connection;
  try {
    const userId = req.user.id;

    connection = await pool.getConnection();
    const [preferences] = await connection.query('SELECT * FROM user_preferences WHERE user_id = ?', [userId]);

    if (preferences.length === 0) {
      // 如果没有偏好设置，可以返回默认值或提示用户设置
      return res.json({
        success: true,
        data: {
          theme: 'light',
          language: 'zh-CN',
          notifications_enabled: true,
          comfort_temperature_min: 22,
          comfort_temperature_max: 28,
          comfort_humidity_min: 40,
          comfort_humidity_max: 65,
          acceptable_aqi_limit: 100,
          pressure_range_min: 980,
          pressure_range_max: 1020,
          light_range_min: 20,
          light_range_max: 80
        }
      });
    }

    const userPref = preferences[0];
    res.json({
      success: true,
      data: {
        theme: userPref.theme,
        language: userPref.language,
        notifications_enabled: userPref.notifications_enabled === 1,
        comfort_temperature_min: parseFloat(userPref.comfort_temperature_min),
        comfort_temperature_max: parseFloat(userPref.comfort_temperature_max),
        comfort_humidity_min: parseFloat(userPref.comfort_humidity_min),
        comfort_humidity_max: parseFloat(userPref.comfort_humidity_max),
        acceptable_aqi_limit: parseFloat(userPref.acceptable_aqi_limit),
        light_preference: parseInt(userPref.light_preference),
        pressure_range_min: parseFloat(userPref.pressure_range_min || 980),
        pressure_range_max: parseFloat(userPref.pressure_range_max || 1020),
        light_range_min: parseFloat(userPref.light_range_min || 20),
        light_range_max: parseFloat(userPref.light_range_max || 80)
      }
    });
  } catch (error) {
    console.error('获取用户偏好设置失败:', error);
    res.status(500).json({
      success: false,
      message: '获取用户偏好设置失败',
      error: error.message
    });
  } finally {
    if (connection) {
      connection.release();
    }
  }
}

/**
 * 更新用户偏好设置
 */
async function updateUserPreferences(req, res) {
  try {
    const userId = req.user.id;
    const {
      theme,
      language,
      notifications_enabled,
      comfort_temperature_min,
      comfort_temperature_max,
      comfort_humidity_min,
      comfort_humidity_max,
      acceptable_aqi_limit,
      light_preference,
      pressure_range_min,
      pressure_range_max,
      light_range_min,
      light_range_max
    } = req.body;

    // 构建更新字段和值
    const updateFields = {};
    if (theme !== undefined) updateFields.theme = theme;
    if (language !== undefined) updateFields.language = language;
    if (notifications_enabled !== undefined) updateFields.notifications_enabled = notifications_enabled ? 1 : 0;
    if (comfort_temperature_min !== undefined) updateFields.comfort_temperature_min = parseFloat(comfort_temperature_min);
    if (comfort_temperature_max !== undefined) updateFields.comfort_temperature_max = parseFloat(comfort_temperature_max);
    if (comfort_humidity_min !== undefined) updateFields.comfort_humidity_min = parseFloat(comfort_humidity_min);
    if (comfort_humidity_max !== undefined) updateFields.comfort_humidity_max = parseFloat(comfort_humidity_max);
    if (acceptable_aqi_limit !== undefined) updateFields.acceptable_aqi_limit = parseFloat(acceptable_aqi_limit);
    if (light_preference !== undefined) updateFields.light_preference = parseInt(light_preference);
    if (pressure_range_min !== undefined) updateFields.pressure_range_min = parseFloat(pressure_range_min);
    if (pressure_range_max !== undefined) updateFields.pressure_range_max = parseFloat(pressure_range_max);
    if (light_range_min !== undefined) updateFields.light_range_min = parseFloat(light_range_min);
    if (light_range_max !== undefined) updateFields.light_range_max = parseFloat(light_range_max);

    if (Object.keys(updateFields).length === 0) {
      return res.status(400).json({
        success: false,
        message: '没有提供要更新的偏好设置'
      });
    }

    // 检查用户偏好记录是否存在，如果不存在则创建
    const [existingPrefs] = await pool.query('SELECT id FROM user_preferences WHERE user_id = ?', [userId]);
    if (existingPrefs.length === 0) {
      await pool.query('INSERT INTO user_preferences (user_id) VALUES (?)', [userId]);
    }

    // 更新用户偏好设置
    await pool.query('UPDATE user_preferences SET ? WHERE user_id = ?', [updateFields, userId]);

    res.json({
      success: true,
      message: '用户偏好设置已更新',
      data: updateFields
    });
  } catch (error) {
    console.error('更新用户偏好设置失败:', error);
    res.status(500).json({
      success: false,
      message: '更新用户偏好设置失败',
      error: error.message
    });
  }
}

/**
 * 获取用户通知设置
 */
async function getNotificationSettings(req, res) {
  let connection;
  try {
    const userId = req.user.id;
    connection = await pool.getConnection();
    const [settings] = await connection.query('SELECT * FROM notification_settings WHERE user_id = ?', [userId]);

    if (settings.length === 0) {
      // 返回默认设置
      return res.json({
        success: true,
        data: {
          enableAll: true,
          
          // 环境提醒
          temperatureRange: true,
          humidityRange: true,
          airQualityThreshold: true,
          pressureRange: false,
          lightRange: false,
          weather: false,
          
          // 设备提醒
          deviceStatus: true,
          deviceError: true,
          autoControl: false,
          pirDetection: false,
          
          // 提醒方式
          vibrate: true,
          sound: true,
          doNotDisturb: false,
          doNotDisturbStart: '22:00',
          doNotDisturbEnd: '07:00',
          
          // 兼容旧版
          email_notifications: true,
          sms_notifications: false,
          push_notifications: true,
          alert_threshold_temperature: 30,
          alert_threshold_humidity: 70,
          alert_threshold_aqi: 150
        }
      });
    }
    
    const userSettings = settings[0];
    // 转换布尔值和数字值
    const convertedSettings = {
      // 通知总开关
      enableAll: userSettings.enable_all === 1,
      
      // 环境提醒
      temperatureRange: userSettings.temperature_range === 1,
      humidityRange: userSettings.humidity_range === 1,
      airQualityThreshold: userSettings.air_quality_threshold === 1,
      pressureRange: userSettings.pressure_range === 1,
      lightRange: userSettings.light_range === 1,
      weather: userSettings.weather === 1,
      
      // 设备提醒
      deviceStatus: userSettings.device_status === 1,
      deviceError: userSettings.device_error === 1,
      autoControl: userSettings.auto_control === 1,
      pirDetection: userSettings.pir_detection === 1,
      
      // 提醒方式
      vibrate: userSettings.vibrate === 1,
      sound: userSettings.sound === 1,
      doNotDisturb: userSettings.do_not_disturb === 1,
      doNotDisturbStart: userSettings.do_not_disturb_start || '22:00',
      doNotDisturbEnd: userSettings.do_not_disturb_end || '07:00',
      
      // 兼容旧版
        email_notifications: userSettings.email_notifications === 1,
        sms_notifications: userSettings.sms_notifications === 1,
        push_notifications: userSettings.push_notifications === 1,
        alert_threshold_temperature: parseFloat(userSettings.alert_threshold_temperature),
        alert_threshold_humidity: parseFloat(userSettings.alert_threshold_humidity),
        alert_threshold_aqi: parseFloat(userSettings.alert_threshold_aqi)
    };
    
    res.json({
      success: true,
      data: convertedSettings
    });
  } catch (error) {
    console.error('获取通知设置失败:', error);
    res.status(500).json({
      success: false,
      message: '获取通知设置失败',
      error: error.message
    });
  } finally {
    if (connection) {
      connection.release();
    }
  }
}

/**
 * 更新用户通知设置
 */
async function updateNotificationSettings(req, res) {
  try {
    const userId = req.user.id;
    const {
      // 通知总开关
      enableAll,
      
      // 环境提醒
      temperatureRange,
      humidityRange,
      airQualityThreshold,
      pressureRange,
      lightRange,
      weather,
      
      // 设备提醒
      deviceStatus,
      deviceError,
      autoControl,
      pirDetection,
      
      // 提醒方式
      vibrate,
      sound,
      doNotDisturb,
      doNotDisturbStart,
      doNotDisturbEnd,
      
      // 兼容旧版
      email_notifications,
      sms_notifications,
      push_notifications,
      alert_threshold_temperature,
      alert_threshold_humidity,
      alert_threshold_aqi
    } = req.body;

    const updateFields = {};
    
    // 处理通知总开关
    if (enableAll !== undefined) updateFields.enable_all = enableAll ? 1 : 0;
    
    // 处理环境提醒
    if (temperatureRange !== undefined) updateFields.temperature_range = temperatureRange ? 1 : 0;
    if (humidityRange !== undefined) updateFields.humidity_range = humidityRange ? 1 : 0;
    if (airQualityThreshold !== undefined) updateFields.air_quality_threshold = airQualityThreshold ? 1 : 0;
    if (pressureRange !== undefined) updateFields.pressure_range = pressureRange ? 1 : 0;
    if (lightRange !== undefined) updateFields.light_range = lightRange ? 1 : 0;
    if (weather !== undefined) updateFields.weather = weather ? 1 : 0;
    
    // 处理设备提醒
    if (deviceStatus !== undefined) updateFields.device_status = deviceStatus ? 1 : 0;
    if (deviceError !== undefined) updateFields.device_error = deviceError ? 1 : 0;
    if (autoControl !== undefined) updateFields.auto_control = autoControl ? 1 : 0;
    if (pirDetection !== undefined) updateFields.pir_detection = pirDetection ? 1 : 0;
    
    // 处理提醒方式
    if (vibrate !== undefined) updateFields.vibrate = vibrate ? 1 : 0;
    if (sound !== undefined) updateFields.sound = sound ? 1 : 0;
    if (doNotDisturb !== undefined) updateFields.do_not_disturb = doNotDisturb ? 1 : 0;
    if (doNotDisturbStart !== undefined) updateFields.do_not_disturb_start = doNotDisturbStart;
    if (doNotDisturbEnd !== undefined) updateFields.do_not_disturb_end = doNotDisturbEnd;
    
    // 处理兼容旧版
    if (email_notifications !== undefined) updateFields.email_notifications = email_notifications ? 1 : 0;
    if (sms_notifications !== undefined) updateFields.sms_notifications = sms_notifications ? 1 : 0;
    if (push_notifications !== undefined) updateFields.push_notifications = push_notifications ? 1 : 0;
    if (alert_threshold_temperature !== undefined) updateFields.alert_threshold_temperature = parseFloat(alert_threshold_temperature);
    if (alert_threshold_humidity !== undefined) updateFields.alert_threshold_humidity = parseFloat(alert_threshold_humidity);
    if (alert_threshold_aqi !== undefined) updateFields.alert_threshold_aqi = parseFloat(alert_threshold_aqi);

    if (Object.keys(updateFields).length === 0) {
      return res.status(400).json({
        success: false,
        message: '没有提供要更新的通知设置'
      });
    }

    // 检查用户通知设置记录是否存在，如果不存在则创建
    const [existingSettings] = await pool.query('SELECT id FROM notification_settings WHERE user_id = ?', [userId]);
    if (existingSettings.length === 0) {
      await pool.query('INSERT INTO notification_settings (user_id) VALUES (?)', [userId]);
    }

    await pool.query('UPDATE notification_settings SET ? WHERE user_id = ?', [updateFields, userId]);

    res.json({
      success: true,
      message: '通知设置已更新',
      data: req.body // 返回客户端传入的格式，而不是数据库格式
    });
  } catch (error) {
    console.error('更新通知设置失败:', error);
    res.status(500).json({
      success: false,
      message: '更新通知设置失败',
      error: error.message
    });
  }
}

/**
 * 获取用户统计数据
 */
async function getUserStatistics(req, res) {
  try {
    const userId = req.user.id;
    
    // 获取用户使用天数 (从用户创建日期计算)
    const [userResult] = await pool.query('SELECT created_at FROM users WHERE id = ?', [userId]);
    
    if (userResult.length === 0) {
      return res.status(404).json({
        success: false,
        message: '用户未找到'
      });
    }
    
    const createdAt = new Date(userResult[0].created_at);
    const now = new Date();
    const usageDays = Math.ceil((now - createdAt) / (1000 * 60 * 60 * 24));
    
    // 这里可以从数据库获取实际的统计数据
    // 以下是模拟数据，实际应用中应该从相应的表中查询
    
    // 节能率计算 (模拟数据)
    const energySaving = '15%';
    
    // 舒适度评分计算 (模拟数据)
    const comfortScore = 89;
    
    res.json({
      success: true,
      data: {
        usageDays,
        energySaving,
        comfortScore
      }
    });
  } catch (error) {
    console.error('获取用户统计数据失败:', error);
    res.status(500).json({
      success: false,
      message: '获取用户统计数据失败',
      error: error.message
    });
  }
}

/**
 * 用户退出登录
 */
async function logoutUser(req, res) {
  try {
    const userId = req.user.id;
    const ipAddress = req.headers['x-forwarded-for'] || req.connection.remoteAddress;
    const userAgent = req.headers['user-agent'] || '';

    // 记录退出登录
    await addAuditLog({
      user_id: userId,
      action: 'logout',
      details: {
        success: true,
        description: '退出登录',
        device_type: parseUserAgent(userAgent)
      },
      ip_address: ipAddress
    });

    // 在实际应用中，可能需要处理token黑名单等逻辑
    // 这里简化处理，直接返回成功
    res.json({
      success: true,
      message: '退出登录成功'
    });
  } catch (error) {
    console.error('退出登录失败:', error);
    res.status(500).json({
      success: false,
      message: '退出登录失败',
      error: error.message
    });
  }
}

/**
 * 解析User-Agent字符串，确定设备类型
 * @param {string} userAgent User-Agent字符串
 * @returns {string} 设备类型描述
 */
function parseUserAgent(userAgent) {
  userAgent = userAgent.toLowerCase();
  
  // 检测设备类型
  if (userAgent.includes('iphone') || userAgent.includes('ipad')) {
    return 'iOS设备';
  } else if (userAgent.includes('android')) {
    return '安卓设备';
  } else if (userAgent.includes('windows')) {
    return 'Windows电脑';
  } else if (userAgent.includes('macintosh') || userAgent.includes('mac os')) {
    return 'Mac电脑';
  } else if (userAgent.includes('linux')) {
    return 'Linux设备';
  } else {
    return '未知设备';
  }
}

// 占位符 - 实际实现需要更复杂的逻辑和数据聚合
async function getEnergyUsageReport(req, res) {
  res.json({ success: true, message: '能源使用报告功能待实现' });
}

async function getComfortReport(req, res) {
  res.json({ success: true, message: '环境舒适度报告功能待实现' });
}

async function getUserActivityHistory(req, res) {
  res.json({ success: true, message: '用户历史记录功能待实现' });
}

module.exports = {
  registerUser,
  loginUser,
  getCurrentUser,
  updateUser,
  changePassword,
  getUserPreferences,
  updateUserPreferences,
  getNotificationSettings,
  updateNotificationSettings,
  getEnergyUsageReport,
  getComfortReport,
  getUserActivityHistory,
  getUserStatistics,
  logoutUser
};